package org.birtserver.backend.service.engine;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;

import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.springframework.beans.factory.annotation.Required;

public class EngineServiceBirtImpl implements EngineService {
  
  private File birtHome;
  
  private IReportEngine engine;
    
  public void init() {
    
    try {
      
      final EngineConfig config = new EngineConfig( );
      config.setEngineHome(birtHome.getAbsolutePath());
      config.setLogConfig(null, Level.FINE);
          
      Platform.startup( config );  //If using RE API in Eclipse/RCP application this is not needed.
      IReportEngineFactory factory = (IReportEngineFactory) Platform
          .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
      
      engine = factory.createReportEngine( config );
      engine.changeLogLevel( Level.WARNING );
      
    } catch (Exception e) {
      throw new RuntimeException("Problem initializing BIRT platform.", e);
    }
    
  }
  
  public void destroy() {
    
    if (engine != null) {
      engine.destroy();  
    }
    
    Platform.shutdown();
    
  }
  
  @Override
  public Design loadDesign(InputStream inputStream) {
    
    try {
      return new Design(engine.openReportDesign(inputStream));
    } catch (Exception e) {
      throw new RuntimeException("Problem opening design.", e);
    }
    
  }
  
  protected IRunAndRenderTask createTask(Design design) {
    return engine.createRunAndRenderTask( design.getDesign() );
  }
  
  @Override
  public void renderHTML(Design design, OutputStream outputStream) {
    
    try {
      
      IRunAndRenderTask task = createTask(design);
      
      HTMLRenderOption options = new HTMLRenderOption();
      //options.setImageHandler( new HTMLServerImageHandler() );
      //options.setImageDirectory( sc.getRealPath("/images");
      //options.setBaseImageURL( req.getContextPath() + "/images" );
      
      options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
      //options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
      options.setOutputStream(outputStream);
      
      task.setRenderOption(options);

      task.run();
      task.close();
      
    } catch (Exception e) {
      throw new RuntimeException("Problem with html rendering.", e);
    }
    
  }
  
  @Required
  public void setBirtHome(File birtHome) {
    this.birtHome = birtHome;
  }
  
}
